package com.vancouver.knows.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.ui.activity.citynews.CityNewsDetailActivity;
import com.vancouver.knows.ui.activity.my.MyAtcommentActivity;
import com.vancouver.knows.ui.activity.my.MyUserPostCommentsActivity;
import com.vancouver.knows.ui.base.LocationActivity;
import com.vancouver.knows.ui.fragment.citydiscount.CityDiscountFragment;
import com.vancouver.knows.ui.fragment.citynews.CityNewsFragment;
import com.vancouver.knows.ui.fragment.event.EventFragment;
import com.vancouver.knows.ui.fragment.homePage.HomeFragment;
import com.vancouver.knows.ui.fragment.my.NewUserFragment;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;

public class MainActivity extends LocationActivity implements NewUserFragment.OnNotificationUpdateListener {

	private FragmentManager fragmentManager;
	private static final String HOME_TAB = "home_tab";
	private static final String CITY_NEWS_TAB = "city_news_tab";
	private static final String EVENT_TAB = "event_tab";
	private static final String CITY_DISCOUNT_TAB = "city_discount_tab";
	private static final String USER_TAB = "user_tab";
	private int mCurrentTabId;
	private String fromOtherWhere = null;

	@Bind(R.id.homeTab)
	RadioButton homeTab;
	@Bind(R.id.cityNewsTab)
	RadioButton cityNewsTab;
	@Bind(R.id.eventTab)
	RadioButton eventTab;
	@Bind(R.id.cityDiscountTab)
	RadioButton cityDiscountTab;
	@Bind(R.id.userTab)
	RadioButton userTab;
	@Bind(R.id.user_notification)
	TextView mUserNotifications;

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void jumpToActivity(String pushValue, String postId){
		if (pushValue == null) {
			return;
		}
		Intent intent = new Intent();
		if ("breaking_news".equals(pushValue)) {
			intent.setClass(this, CityNewsDetailActivity.class);
			intent.putExtra("postId", postId);

		} else if ("new_comment".equals(pushValue)) {
			if (AppUtils.getLoginStatus(imContext)) {
				intent.setClass(this, MyUserPostCommentsActivity.class);
			}

		} else if ("new_reply".equals(pushValue)) {
			if (AppUtils.getLoginStatus(imContext)) {
				intent.setClass(this, MyAtcommentActivity.class);
			}

		} else {
			if (AppUtils.getLoginStatus(imContext)) {
				intent.setClass(this, MainActivity.class);
			}
		}
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		imContext.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		fcmNnotificationData();
		initView();
		setNotifications();
	}

	private void fcmNnotificationData() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle == null) return;

		String pushValue = null;
		String postId = null;
		for (String key : getIntent().getExtras().keySet()) {
			Object value = getIntent().getExtras().get(key);
			Log.d(TAG, "Key: " + key + " Value: " + value);
			if ("notification_type".equals(key)) {
				pushValue = (String) value;

			}

			if ("post_id".equals(key)) {
				postId = (String) value;

			} else {
				//....
			}
		}

		jumpToActivity(pushValue, postId);
	
	}

	private void setNotifications() {
		BSharedPrefManager sharedPrefManager = imContext.getSharedPrefManager();
		if (sharedPrefManager != null && sharedPrefManager.getUserId() != null) {
			if (sharedPrefManager.getCloseAllMessage()) {
				int notificationCount = 0;
				if (sharedPrefManager.getMyArticleNewComment() && !sharedPrefManager.getTotalUnReadPostComment().equals("0")) {
					notificationCount += Integer.valueOf(sharedPrefManager.getTotalUnReadPostComment());
				}

				if (sharedPrefManager.getHaveAtCommentMessage() && !sharedPrefManager.getTotalUnReadComment().equals("0")) {
					notificationCount += Integer.valueOf(sharedPrefManager.getTotalUnReadComment());
				}

				if (notificationCount != 0) {
					mUserNotifications.setText(String.valueOf(notificationCount));
					mUserNotifications.setVisibility(View.VISIBLE);
				} else {
					mUserNotifications.setVisibility(View.GONE);
				}
			}
		} else {
			mUserNotifications.setVisibility(View.GONE);
		}
	}

	private void initView() {
		fragmentManager = getSupportFragmentManager();
		mCurrentTabId = R.id.homeTab;
		showFragment(R.id.homeTab, 0);
	}

	@OnClick({R.id.homeTab, R.id.cityNewsTab, R.id.eventTab, R.id.cityDiscountTab, R.id.userTab})
	public void onTabClicked(RadioButton tab) {
		int tabId = tab.getId();
		boolean isTabReselected = mCurrentTabId == tabId;

		switch (tabId) {

			case R.id.homeTab:
				if (isTabReselected) {
					HomeFragment homeFragment = (HomeFragment) fragmentManager.findFragmentByTag(HOME_TAB);
					if (homeFragment != null) {
						homeFragment.scrollUp();
					}
				}
				break;

			case R.id.cityNewsTab:
				if (isTabReselected) {
					CityNewsFragment cityNewsFragment = (CityNewsFragment) fragmentManager.findFragmentByTag(CITY_NEWS_TAB);
					if (cityNewsFragment != null) {
						cityNewsFragment.scrollUp();
					}
				}
				break;

			case R.id.cityDiscountTab:
				if (isTabReselected) {
					CityDiscountFragment cityDiscountFragment = (CityDiscountFragment) fragmentManager.findFragmentByTag(CITY_DISCOUNT_TAB);
					if (cityDiscountFragment != null) {
						cityDiscountFragment.scrollUp();
					}
				}

				break;

			case R.id.eventTab:
				if (isTabReselected) {
					EventFragment eventFragment = (EventFragment) fragmentManager.findFragmentByTag(EVENT_TAB);
					if (eventFragment != null) {
						eventFragment.scrollUp();
					}
				}
				break;

			case R.id.userTab:
				if (isTabReselected) {
					NewUserFragment userFragment = (NewUserFragment) fragmentManager.findFragmentByTag(USER_TAB);
					if (userFragment != null) {
						userFragment.scrollUp();
					}
				}
				break;

		}

		mCurrentTabId = tabId;
	}

	@OnCheckedChanged(R.id.homeTab)
	public void onHomeTabChecked(boolean checked) {
		if (checked) {
			showFragment(R.id.homeTab, 0);

			Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
			t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
			t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_TABBAR_BTN)
					.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(AnalyticsConstants.LABEL_TABBAR_HOME_BTN)
					.build());
		}

	}

	@OnCheckedChanged(R.id.cityNewsTab)
	public void onCityNewsTabChecked(boolean checked) {
		if (checked) {
			showFragment(R.id.cityNewsTab, 0);

			Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
			t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
			t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_TABBAR_BTN)
					.setAction(AnalyticsConstants.ACTION_ONCLICK)
					.setLabel(AnalyticsConstants.LABEL_TABBAR_CITYNEWS_BTN).build());
		}
	}

	@OnCheckedChanged(R.id.eventTab)
	public void onEventTabChecked(boolean checked) {
		if (checked) {
			showFragment(R.id.eventTab, 0);

			Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
			t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
			t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_TABBAR_BTN)
					.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(AnalyticsConstants.LABEL_TABBAR_EVENT_BTN)
					.build());
		}
	}

	@OnCheckedChanged(R.id.cityDiscountTab)
	public void onCityDiscountTabChecked(boolean checked) {
		if (checked) {
			if (fromOtherWhere == null) {
				showFragment(R.id.cityDiscountTab, 0);
			}else if ("fromOther".equals(fromOtherWhere)){
				showCityDiscountTab();
			}

			Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
			t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
			t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_TABBAR_BTN)
					.setAction(AnalyticsConstants.ACTION_ONCLICK)
					.setLabel(AnalyticsConstants.LABEL_TABBAR_CITYDISCOUNT_BTN).build());
		}
	}

	@OnCheckedChanged(R.id.userTab)
	public void onUserTabChecked(boolean checked) {
		if (checked) {
			showFragment(R.id.userTab, 0);
			Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
			t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
			t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_TABBAR_BTN)
					.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(AnalyticsConstants.LABEL_TABBAR_MY_BTN)
					.build());
		}
	}

	@Override
	public void subHandleMessage(Message msg) {
		super.subHandleMessage(msg);

		switch (msg.what) {
		case Constants.BUSINESS_STATUS_EVENT_LIST_HEAD_POSTS_CHANGE: {
			EventFragment eventFragment = (EventFragment) fragmentManager.findFragmentByTag(EVENT_TAB);
			if (eventFragment != null) {
				eventFragment.subHandleMessage(msg);
			}
		}
			break;
		}
	}

	public void showCityDiscountTab() {
		fromOtherWhere = "fromOther";
		if (!cityDiscountTab.isChecked()) {
			cityDiscountTab.setChecked(true);
		}

		fromOtherWhere = null;
		Fragment fragment = fragmentManager.findFragmentByTag(CITY_DISCOUNT_TAB);
		if (fragment == null) {
			fragment = CityDiscountFragment.newInstance();
		}

		fragmentManager.beginTransaction()
				.replace(R.id.mainContent, fragment, CITY_DISCOUNT_TAB)
				.addToBackStack(null)
				.commitAllowingStateLoss();
	}

	public void showFragment(int res, int suIndex) {
		Fragment fragment = null;
		String fragmentTab = HOME_TAB;

		switch (res) {
		case R.id.homeTab:
			if (!homeTab.isChecked()) {
				homeTab.setChecked(true);
			}

			fragment = fragmentManager.findFragmentByTag(HOME_TAB);
			if (fragment == null) {
				fragment = HomeFragment.newInstance();
			}
			fragmentTab = HOME_TAB;
			break;

		case R.id.cityNewsTab:
			if (!cityNewsTab.isChecked()) {
				cityNewsTab.setChecked(true);
			}

			fragment = fragmentManager.findFragmentByTag(CITY_NEWS_TAB);
			if (fragment == null) {
				fragment = CityNewsFragment.newInstance();
			}
			//((CityNewsFragment) fragment).setToIndex(suIndex);
			fragmentTab = CITY_NEWS_TAB;
			break;

		case R.id.eventTab:
			if (!eventTab.isChecked()) {
				eventTab.setChecked(true);
			}

			fragment = fragmentManager.findFragmentByTag(EVENT_TAB);
			if (fragment == null) {
				fragment = EventFragment.newInstance();
			}
			fragmentTab = EVENT_TAB;
			break;

		case R.id.cityDiscountTab:
			if (!cityDiscountTab.isChecked()) {
				cityDiscountTab.setChecked(true);
			}

			fragment = fragmentManager.findFragmentByTag(CITY_DISCOUNT_TAB);
			if (fragment == null) {
				fragment = CityDiscountFragment.newInstance();
			}
			fragmentTab = CITY_DISCOUNT_TAB;
			break;

		case R.id.userTab:
			if (!userTab.isChecked()) {
				userTab.setChecked(true);
			}

			fragment = fragmentManager.findFragmentByTag(USER_TAB);
			if (fragment == null) {
				fragment = NewUserFragment.newInstance();
			}

			fragmentTab = USER_TAB;
			break;
		}
		fragmentManager.beginTransaction().replace(R.id.mainContent, fragment, fragmentTab).commit();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
			exitApp();
			return false;
		}
		return true;
	}

	// 定义一个变量，来标识是否退出
	private static boolean isExit = false;
	@SuppressLint("HandlerLeak")
	Handler mHandlerQuit = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}
	};

	private void exitApp() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(this,this.getString(R.string.quit_app), Toast.LENGTH_SHORT).show();
			// 利用handler延迟发送更改状态信息
			mHandlerQuit.sendEmptyMessageDelayed(0, 3000);
		} else {
			finish();
			System.exit(0);
		}
	}

	@Override
	public void onNotificationUpdate() {
		setNotifications();
	}
}
